﻿using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Collections;

public class PersonData : IData
{
    public Action m_callBack = null;

    private bool hasCheck = false;

    private string jsData_Current = null;
    private string jsData_Previous = null;

    private string _root = "list";
    private string _id = "id";
    private string _updataTime = "updataTime";

    private Queue<string> dataContainer = new Queue<string>();
    private int totalLoading = 0;

    /// <summary>
    /// 检查更新
    /// </summary>
    /// <param name="callBack"></param>
    private void CheckData(Action callBack)
    {
        hasCheck = false;
        Dictionary<string, object> temp_cur = MiniJSON.Json.Deserialize(jsData_Current) as Dictionary<string, object>;
        Dictionary<string, object> temp_pre = MiniJSON.Json.Deserialize(jsData_Previous) as Dictionary<string, object>;
        List<object> curResult = new List<object>();
        List<object> preResult = new List<object>();

        curResult = temp_cur[_root] as List<object>;
        if (jsData_Previous != null)
            preResult = temp_pre[_root] as List<object>;
        Debug.Log("cur:" + curResult.Count + " pre:" + preResult.Count);
        //Dictionary<string, object> temp_cur = new Dictionary<string, object>();
        //Dictionary<string, object> temp_pre = new Dictionary<string, object>();
        string itemID_cur;
        string itemID_pre;
        //1.先把需要更新的放到 链表上
        foreach (var item_cur in curResult)
        {
            temp_cur = item_cur as Dictionary<string, object>;
            itemID_cur = temp_cur[_id].ToString();
            string path = LocalResourcePath.GetInstance().PersonImage("/" + itemID_cur + "/");
            if (!Directory.Exists(path) || string.IsNullOrEmpty(jsData_Previous) || Directory.GetFiles(path).Length == 0)
            {
                if (Directory.Exists(path)) Directory.Delete(path, true);
                dataContainer.Enqueue(itemID_cur);
            }
            else
            {
                foreach (var item_pre in preResult)
                {
                    temp_pre = item_pre as Dictionary<string, object>;
                    itemID_pre = temp_pre[_id].ToString();
                    if (item_pre.Equals(item_cur))
                    {
                        if (!temp_cur[_updataTime].ToString().Equals(temp_pre[_updataTime].ToString()))
                        {
                            if (Directory.Exists(path)) Directory.Delete(path, true);
                            dataContainer.Enqueue(itemID_cur);
                        }
                        break;
                    }
                }
            }
        }

        int count = 0;
        string[] dirs;
        string dirName = "";
        //2.匹配旧的数据
        if (Directory.Exists(LocalResourcePath.GetInstance().ResourceRoot))
        {
            dirs = Directory.GetDirectories(LocalResourcePath.GetInstance().ResourceRoot);
            foreach (var item_dir in dirs)
            {
                dirName = item_dir.Remove(0, item_dir.LastIndexOf("\\") + 1);
                foreach (var item in curResult)
                {
                    temp_cur = item as Dictionary<string, object>;
                    if(dirName == temp_cur[_id].ToString())
                    {
                        count = 0;
                        break;
                    }
                    else if (++count >= curResult.Count)
                    {
                        count = 0;
                        if (Directory.Exists(item_dir)) Directory.Delete(item_dir, true);
                    }
                }
            }
        }

        totalLoading = dataContainer.Count;
        LoadingProgress = 0;
        callBack();
    }

    string ID = "";
    /// <summary>
    /// 下载数据
    /// </summary>
    void DownLoadAsset()
    {
        if(dataContainer.Count>0)
        {
            LoadingProgress = (float)(totalLoading - dataContainer.Count) / totalLoading;
            ID = dataContainer.Dequeue();
            Dictionary<string, object> cur = MiniJSON.Json.Deserialize(jsData_Current) as Dictionary<string, object>;
            List<object> result = cur[_root] as List<object>;
            Dictionary<string, object> persionData = new Dictionary<string, object>();
            foreach (var item in result)
            {
                persionData = item as Dictionary<string, object>;
                if (persionData[_id].ToString() == ID)
                {
                    if (!Directory.Exists(LocalResourcePath.GetInstance().PersonImage("/" + ID + "/"))) 
                        Directory.CreateDirectory(LocalResourcePath.GetInstance().PersonImage("/" + ID + "/"));
                    
                    File.WriteAllText(LocalResourcePath.GetInstance().PersonConfig("/" + ID + "/"), MiniJSON.Json.Serialize(persionData), Encoding.UTF8);

                    string path = persionData["img"].ToString();
                    if (!string.IsNullOrEmpty(path))
                    {
                        Loader.GetInstance().SendMessage_GET(path, SavePersionData);
                    }
                    else
                    {
                        DownLoadAsset();
                    }
                    break;
                }
            }
            
        }
        else
        {
            LoadingProgress = 1;
            if (!Directory.Exists(LocalResourcePath.GetInstance().ConfigPath())) Directory.CreateDirectory(LocalResourcePath.GetInstance().ConfigPath());
            File.WriteAllText(LocalResourcePath.GetInstance().ConfigPath(true), jsData_Current);

            //加载完成，执行下一步
            Loader.GetInstance().SetSynergyFunc(loadNextPanel());
        }
    }

    private IEnumerator loadNextPanel()
    {
        yield return new WaitForSeconds(1.0f);
        m_callBack();
    }
    /// <summary>
    /// 保存图片
    /// </summary>
    /// <param name="www"></param>
    private void SavePersionData(WWW www)
    {
        if (www.error == null)
        {
            Texture2D tex = new Texture2D(www.texture.width, www.texture.height);
            www.LoadImageIntoTexture(tex);
            File.WriteAllBytes(LocalResourcePath.GetInstance().PersonImage("/" + ID + "/") + "/index.png", tex.EncodeToPNG());
        }
        else
        {
            Debug.Log(www.error);
        }
        
        DownLoadAsset();
    }

    //-----------------------------------------------------------------------------------------//

    /// <summary>
    /// 获取所有数据
    /// </summary>
    /// <returns></returns>
    public Dictionary<string, object> GetData()////////////////////////////////
    {
        Dictionary<string, object> _data = new Dictionary<string, object>();
        string jsonPath = LocalResourcePath.GetInstance().ConfigPath(true);
        Dictionary<string, object> jsData = MiniJSON.Json.Deserialize(File.ReadAllText(jsonPath, Encoding.UTF8)) as Dictionary<string, object>;
        List<object> result = jsData[_root] as List<object>;

        Dictionary<string, object> temp = new Dictionary<string, object>();
        foreach (var item in result)
        {
            temp = item as Dictionary<string, object>;

            Person person = new Person();
            person.id = temp[_id].ToString();
            person.name = temp["name"].ToString();
            person.level = temp["position"].ToString();
            person.jodDes = temp["labe"].ToString();
            person.intro = temp["des"].ToString();
            person.speciality = temp["bestG"].ToString();

            _data.Add(temp[_id].ToString(), person);
        }
        return _data;
    }

    /// <summary>
    /// 根据ID查找对象
    /// </summary>
    /// <param name="Key">ID</param>
    /// <returns></returns>
    public object GetDataWithKey(string Key)
    {
        foreach (var item in GetData())
        {
            if (item.Key == Key)
                return item.Value;
        }
        return null;
    }

    /// <summary>
    /// 下载进度
    /// </summary>
    /// <returns></returns>
    private event DelegateEvent.DataChangeEvent OnPrcentChange;
    public DelegateEvent.DataChangeEvent AddPrecentEvent
    {
        get { return OnPrcentChange; }
        set { OnPrcentChange = value; }
    }

    private float _currentProgress = -1;
    public float LoadingProgress
    {
        get { return _currentProgress; }
        set
        {
            if (_currentProgress == value) return;
            _currentProgress = value;
            if (OnPrcentChange != null) OnPrcentChange(_currentProgress);
        }
    }
    #region 遗弃方法
    private float _LoadingProgress()
    {
        if (hasCheck)
        {
            if (totalLoading != 0)
            {
                return (float)(totalLoading - dataContainer.Count) / totalLoading;
            }
            else
            {
                return 100;
            }
        }
        return 0;
    }
    #endregion
    

    /// <summary>
    /// 转化数据入口
    /// </summary>
    /// <param name="json"></param>
    /// <param name="callBack"></param>
    public void Translate2String(string json,Action callBack)
    {
        jsData_Current = json;
        m_callBack = callBack;
        string path = LocalResourcePath.GetInstance().ConfigPath(true);
        if (File.Exists(path))
            jsData_Previous = File.ReadAllText(path, Encoding.UTF8);
        
        CheckData(DownLoadAsset);
    }
}

public struct Person//////////////////////
{
    //人物的属性

    public string id;
    public string name;
    public string level;
    public string jodDes;
    public string intro;
    public string speciality;
}
